package org.yan.kangaroo.auth.config.security.provider;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.yan.kangaroo.auth.config.security.SecurityUserDetails;
import org.yan.kangaroo.auth.config.security.token.EmailVerifyCodeAuthenticationToken;
import org.yan.kangaroo.auth.service.UserAuthService;
import org.yan.kangaroo.auth.service.UserService;
import org.yan.kangaroo.pojo.ucenter.constant.UserAuthIdentityTypeEnum;
import org.yan.kangaroo.pojo.ucenter.entity.User;
import org.yan.kangaroo.pojo.ucenter.entity.UserAuth;

/**
 * 用户名密码登录加验证码登录
 *
 * @author wangx
 * @date 11/13/2019 9:13
 */

@Component
@Slf4j
public class EmailVerifyCodeAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private UserAuthService userAuthService;

    @Autowired
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        log.info("[authenticate] username:{},password:{}", authentication.getPrincipal(), authentication.getCredentials());
        String email = authentication.getPrincipal().toString();
        UserAuth userAuth = userAuthService.findByIdentifierAndIdentityType(email, UserAuthIdentityTypeEnum.EMAIl.getType());
        if (userAuth == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        User user = userService.findByAccountId(userAuth.getAccountId());
        SecurityUserDetails userDetails = new SecurityUserDetails(user, email, userAuth.getCredential());
        EmailVerifyCodeAuthenticationToken emailVerifyCodeAuthenticationToken = new EmailVerifyCodeAuthenticationToken(userDetails, "", null);
        log.info("[authenticate] token:{}", emailVerifyCodeAuthenticationToken);
        return emailVerifyCodeAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(EmailVerifyCodeAuthenticationToken.class);
    }
}
